package ru.weho.osmwidget;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.RemoteViews;

public class OSMUpdateService extends Service {
	@SuppressWarnings("unused")
	private static final String TAG = "OSMUpdateService";

	static LocationManager locMan;
	static Location curLocation;
	static boolean gotFix;

    LocationListener gpsListener = new LocationListener() {
    	public void onLocationChanged(Location location) {
    		curLocation = location;

    		Context context = getApplicationContext();
    		RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    		ComponentName provider = new ComponentName(context, OSMWidgetProvider.class);
        	AppWidgetManager manager = AppWidgetManager.getInstance(context);
        	int[] appWidgetIds = manager.getAppWidgetIds(provider);

        	SharedPreferences prefs = getApplicationContext().getSharedPreferences(OSMWidgetConfigure.PREFS_NAME, 0);

        	for (int appWidgetId: appWidgetIds) {
        		int zoom = prefs.getInt(OSMWidgetConfigure.ZOOM_KEY + appWidgetId, OSMWidgetConfigure.defaultZoom);
        		float density = prefs.getFloat(OSMWidgetConfigure.DENSITY, 1);
        		String maptype = prefs.getString(OSMWidgetConfigure.MAPTYPE_KEY + appWidgetId, "mapnik");

            	OSMBitmap osmBitmap = new OSMBitmap(curLocation, zoom, density, maptype);
        		Bitmap bitmap = osmBitmap.loadRemoteBitmap();
        		if (bitmap != null) {
        			updateViews.setImageViewBitmap(R.id.MapImageView, bitmap);
        		}
        		manager.updateAppWidget(appWidgetId, updateViews);
        	}

        	if (!gotFix) {
	        	if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
	        		locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, gpsListener);
	        	}
	        	else if (locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
	        		locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, gpsListener);
	        	}
	        	gotFix = true;
        	}
    	}

    	public void onProviderDisabled(String provider) {
    		locMan.removeUpdates(gpsListener);
    	}

    	public void onProviderEnabled(String provider) {
        	if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        		locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, gpsListener);
        	}
        	else if (locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        		locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, gpsListener);
        	}
    	}

    	public void onStatusChanged(String provider, int status, Bundle extras) {
    		if (status == 0) {// UnAvailable
    		}
    		else if (status == 1) {// Trying to Connect
    		}
    		else if (status == 2) {// Available
    		}
    	}
    };

    @Override
    public void onStart(Intent intent, int startId) {
    	gotFix = false;
    	locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    		locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
    	}
    	else if (locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    		locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, gpsListener);
    	}
    	else {
    		Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		startActivity(i);
    	}
    }

    @Override
    public void onDestroy() {
    	locMan.removeUpdates(gpsListener);
    	super.onDestroy();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0) {
            String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if (provider != null) {
                if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            		locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
            	}
                else if (locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                	locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, gpsListener);
                }
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
